package com.alibaba.citrus.cr.common.util;

import org.apache.commons.collections4.CollectionUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class ObjectNullUtil {

    public static boolean objectIsNull(Object obj) {
        if (obj == null) {
            return true;
        }
        //获取所有属性
        Field[] fields = obj.getClass().getDeclaredFields();
        if (fields.length == 0) {
            return true;
        }
        boolean flag = true;
        for (Field field : fields) {
            //不检查，设置可访问
            field.setAccessible(true);
            try {
                if (field.get(obj) instanceof Collection) {
                    if (isNotNull((Collection) field.get(obj))) {
                        flag = false;
                        break;
                    }
                } else {
                    if (isNotNull(field.get(obj))) {
                        flag = false;
                        break;
                    }
                }
            } catch (Exception e) {
                flag = false;
            }
        }
        return flag;
    }

    public static boolean isNull(Object obj) {
        return obj == null || isNull(obj.toString());
    }

    public static boolean isNull(Collection collection) {
        return collection == null || collection.isEmpty();
    }

    public static boolean isNull(String str) {
        return str == null || str.trim().isEmpty() || "null".equalsIgnoreCase(str);
    }

    public static boolean isNotNull(Collection collection) {
        return !isNull(collection);
    }

    public static boolean isNotNull(Object obj) {
        return !isNull(obj);
    }

    public static boolean isAllFieldNull(Object o, List<String> ignoreFields) {
        try {
            if (CollectionUtils.isEmpty(ignoreFields)) {
                ignoreFields = new ArrayList<>();
            }
            ignoreFields.add("serialVersionUID");
            for (Field field : o.getClass().getDeclaredFields()) {
                //把私有属性公有化
                field.setAccessible(true);
                Object object = field.get(o);
                if (object != null && !ignoreFields.contains(field.getName())) {
                    return false;
                }
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
